package com.example.simpleforum.dao;

import com.example.simpleforum.model.Reply;
import com.example.simpleforum.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 回复数据访问对象
 */
public class ReplyDao {
    
    /**
     * 添加新回复
     * @param reply 回复对象
     * @return 新增回复的ID，失败返回-1
     */
    public int addReply(Reply reply) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int replyId = -1;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO reply (content, user_id, post_id, create_time, update_time) VALUES (?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, reply.getContent());
            pstmt.setInt(2, reply.getUserId());
            pstmt.setInt(3, reply.getPostId());
            pstmt.setTimestamp(4, reply.getCreateTime());
            pstmt.setTimestamp(5, reply.getUpdateTime());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    replyId = rs.getInt(1);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return replyId;
    }
    
    /**
     * 更新回复
     * @param reply 回复对象
     * @return 更新成功返回true，失败返回false
     */
    public boolean updateReply(Reply reply) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE reply SET content = ?, update_time = ? WHERE id = ? AND user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, reply.getContent());
            pstmt.setTimestamp(2, reply.getUpdateTime());
            pstmt.setInt(3, reply.getId());
            pstmt.setInt(4, reply.getUserId());
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 删除回复
     * @param replyId 回复ID
     * @param userId 用户ID（确保只能删除自己的回复）
     * @return 删除成功返回true，失败返回false
     */
    public boolean deleteReply(int replyId, int userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM reply WHERE id = ? AND user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, replyId);
            pstmt.setInt(2, userId);
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 根据ID查询回复
     * @param id 回复ID
     * @return 回复对象，不存在则返回null
     */
    public Reply findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Reply reply = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT r.*, u.username FROM reply r JOIN user u ON r.user_id = u.id WHERE r.id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                reply = new Reply();
                reply.setId(rs.getInt("id"));
                reply.setContent(rs.getString("content"));
                reply.setUserId(rs.getInt("user_id"));
                reply.setPostId(rs.getInt("post_id"));
                reply.setUsername(rs.getString("username"));
                reply.setCreateTime(rs.getTimestamp("create_time"));
                reply.setUpdateTime(rs.getTimestamp("update_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return reply;
    }
    
    /**
     * 查询指定帖子的所有回复
     * @param postId 帖子ID
     * @return 回复列表
     */
    public List<Reply> findRepliesByPostId(int postId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Reply> replies = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT r.*, u.username FROM reply r JOIN user u ON r.user_id = u.id WHERE r.post_id = ? ORDER BY r.create_time ASC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Reply reply = new Reply();
                reply.setId(rs.getInt("id"));
                reply.setContent(rs.getString("content"));
                reply.setUserId(rs.getInt("user_id"));
                reply.setPostId(rs.getInt("post_id"));
                reply.setUsername(rs.getString("username"));
                reply.setCreateTime(rs.getTimestamp("create_time"));
                reply.setUpdateTime(rs.getTimestamp("update_time"));
                replies.add(reply);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return replies;
    }
    
    /**
     * 查询指定用户的所有回复
     * @param userId 用户ID
     * @return 回复列表
     */
    public List<Reply> findRepliesByUserId(int userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Reply> replies = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT r.*, u.username FROM reply r JOIN user u ON r.user_id = u.id WHERE r.user_id = ? ORDER BY r.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Reply reply = new Reply();
                reply.setId(rs.getInt("id"));
                reply.setContent(rs.getString("content"));
                reply.setUserId(rs.getInt("user_id"));
                reply.setPostId(rs.getInt("post_id"));
                reply.setUsername(rs.getString("username"));
                reply.setCreateTime(rs.getTimestamp("create_time"));
                reply.setUpdateTime(rs.getTimestamp("update_time"));
                replies.add(reply);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return replies;
    }
}